package com.codemonkey.lq.qd.extend.impl;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {

	private static final String CONFIG_FILE_CLASSPATH = "config/mybatis-config.xml";

	private static final Configuration configuration;

	static {
		
		/* 适合在没有Spring作为容器的情况下*/
		configuration = getSqlSessionFactoryUsingSpecialXML(CONFIG_FILE_CLASSPATH)
				.getConfiguration();
		 
	}

	private static SqlSessionFactory getSqlSessionFactoryUsingSpecialXML(String xmlConfigFilePath) {
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream(xmlConfigFilePath);
			SqlSessionFactory xmlSqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);

			return xmlSqlSessionFactory;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取MyBatis的Configuration对象,从而利用mybatis的内置功能来帮助我们生成sql
	 * @return
	 */
	public static Configuration getConfiguration() {
		if (configuration == null) {
			throw new IllegalArgumentException("configuration is null !!!");
		}

		return configuration;
	}

	public static String getSQL(String sqlId, Object arg) {
		if (configuration == null) {
			throw new IllegalArgumentException("configuration is null !!!");
		}
		
		return configuration.getMappedStatement(sqlId).getBoundSql(arg).getSql();
	}
}
